(function () {
    var core = ecui,
        util = core.util,
        dom = ecui.dom,
        ui = core.ui;

    function getWeeks(year) {
        var weeks = [],
            i = 0,
            now = new Date(),
            start = new Date(year, 0, 1),
            end = new Date(year + 1, 0, 1);

        if (start.getDay() !== 1) {
            weeks.push({
                index: ++i,
                start: start,
                end: new Date(year, 0, 7 - start.getDay())
            });
        }
        start = new Date(year, 0, 8 - start.getDay());
        end = end < now ? end : now;
        for (; start < end; ) {
            var endDay = new Date(year, start.getMonth(), start.getDate() + 6);
            if (endDay >= end) {
                weeks.push({
                    index: ++i,
                    start: start,
                    end: new Date(year, start.getMonth(), start.getDate() + end.getDay() - 1)
                });
            } else {
                weeks.push({
                    index: ++i,
                    start: start,
                    end: new Date(year, start.getMonth(), start.getDate() + 6)
                });
            }
            start = new Date(year, start.getMonth(), start.getDate() + 7);
        }
        return weeks.reverse();
    }
    var now = new Date(),
        year = now.getFullYear(),
        period = [];
    for (var i = 0; i < 5; i++) {
        period.push({ year: year - i, weeks: getWeeks(year - i)});
    }
    now = { year: now.getFullYear(), month: now.getMonth() + 1, day: now.getDate() };

    ecui.util.extend(NS.ui, {
        /**
         * 操作按钮控件。
         * 统计栏切换场馆按钮
         * @control
         */
        VenueSelect: ecui.inherits(
            ui.Control,
            {
                onclick: function () {
                    var venueId = document.forms.indexStatisticsForm.elements.venueId.value;
                    ecui.esr.showSelect(ecui.esr.getEngine().render('index_venue_single_select', { 'items': mao.venues, value: venueId }), function (event) {
                        venueId.value = event.item.getValue();
                        dom.first(this.getMain()).innerHTML = event.item.getText();
                        util.timer(function () {
                            ecui.esr.callRoute('/home/statistics', true);
                        }, 300);
                    }.bind(this), '场馆');
                }
            }
        ),
        Message: ecui.inherits(
            ecui.ui.Control,
            {
                onclick: function () {
                    if (ecui.esr.getGlobal().isLogin) {
                        ecui.esr.redirect('/message/message');
                        ecui.esr.delegate('/message/message', 'CACHE', undefined);
                    } else {
                        window.callBridge('login'); //调用原生的桥，跳转到登录页面
                    }
                }
            }
        ),
        HasDrink: ecui.inherits(
            ecui.ui.Checkbox,
            {
                onclick: function () {
                    util.timer(function () {
                        ecui.esr.callRoute('/home/statistics', true);
                    }, 0);
                }
            }
        ),
        Prev: ecui.inherits(
            ecui.ui.Control,
            {
                onclick: function () {
                    var route = ecui.esr.getRoute('/home/index'),
                        form = document.forms.indexStatisticsForm,
                        elements = form.elements,
                        textEl = dom.children(form)[1],

                        mtype = route.mtype,
                        year = route.year,
                        index = route.index;

                    if (mtype === 'month') {
                        if (index === 1) {
                            route.year = route.year - 1;
                            route.index = 12;
                        } else {
                            route.index = route.index - 1;
                        }

                        elements.startDate.value = new Date(route.year, route.index - 1, 1).pattern('yyyy-MM-dd');
                        elements.endDate.value = new Date(route.year, route.index, 0).pattern('yyyy-MM-dd');

                        textEl.innerHTML = '月收入' + route.year + '年' + route.index + '月';
                    } else {
                        for (var i = 0, item; item = period[i++]; ) {
                            if (year === item.year) {
                                if (index === 1) {
                                    // 某年的第一周
                                    var item1 = period[i];
                                    if (!item1) {
                                        return;
                                    }
                                    route.year = item1.year;
                                    route.index = item1.weeks[0].index;

                                    elements.startDate.value = item1.weeks[0].start.pattern('yyyy-MM-dd');
                                    elements.endDate.value = item1.weeks[0].end.pattern('yyyy-MM-dd');

                                    textEl.innerHTML = '周收入' + route.year + '年第' + route.index + '周';
                                } else {
                                    for (var k = 0, _item; _item = item.weeks[k++]; ) {
                                        if (_item.index === index) {

                                            route.index = item.weeks[k].index;
                                            elements.startDate.value = item.weeks[k].start.pattern('yyyy-MM-dd');
                                            elements.endDate.value = item.weeks[k].end.pattern('yyyy-MM-dd');

                                            textEl.innerHTML = '周收入' + route.year + '年第' + route.index + '周';
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    ecui.esr.callRoute('/home/statistics', true);
                }
            }
        ),
        Next: ecui.inherits(
            ecui.ui.Control,
            {
                onclick: function () {
                    var route = ecui.esr.getRoute('/home/index'),
                        form = document.forms.indexStatisticsForm,
                        elements = form.elements,
                        textEl = dom.children(form)[1],

                        mtype = route.mtype,
                        year = route.year,
                        index = route.index;

                    if (mtype === 'month') {
                        if (index === 12) {
                            route.year = route.year + 1;
                            route.index = 1;
                        } else {
                            route.index = route.index + 1;
                        }

                        elements.startDate.value = new Date(route.year, route.index - 1, 1).pattern('yyyy-MM-dd');
                        elements.endDate.value = new Date(route.year, route.index, 0).pattern('yyyy-MM-dd');

                        textEl.innerHTML = '月收入' + route.year + '年' + route.index + '月';
                    } else {
                        for (var i = 0, item; item = period[i++]; ) {
                            if (year === item.year) {
                                if (index === item.weeks[0].index) {
                                    // 某年的最后一周
                                    var item1 = period[i - 2];
                                    if (!item1) {
                                        return;
                                    }
                                    route.year = item1.year;
                                    route.index = item1.weeks.slice(-1)[0].index;

                                    elements.startDate.value = item1.weeks.slice(-1)[0].start.pattern('yyyy-MM-dd');
                                    elements.endDate.value = item1.weeks.slice(-1)[0].end.pattern('yyyy-MM-dd');

                                    textEl.innerHTML = '周收入' + route.year + '年第' + route.index + '周';
                                } else {
                                    for (var k = 0, _item; _item = item.weeks[k++]; ) {
                                        if (_item.index === index) {
                                            route.index = item.weeks[k - 2].index;

                                            elements.startDate.value = item.weeks[k - 2].start.pattern('yyyy-MM-dd');
                                            elements.endDate.value = item.weeks[k - 2].end.pattern('yyyy-MM-dd');

                                            textEl.innerHTML = '周收入' + route.year + '年第' + route.index + '周';
                                            break;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    ecui.esr.callRoute('/home/statistics', true);
                }
            }
        ),

        /**
         * 操作按钮控件。
         * 打开二维码验票按钮
         * @control
         */
        VerifyBtn: ecui.inherits(
            ecui.ui.Control,
            {
                onclick: function () {
                    wx.scanQRCode({
                        needResult: 1, // 默认为0，扫描结果由微信处理，1则直接返回扫描结果，
                        scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码，默认二者都有
                        success: function (res) {
                            var result = res.resultStr; // 当needResult 为 1 时，扫码返回的结果
                            // 请求www.showstart.com资源时，跨域报错
                            ecui.esr.redirect('/integral/goods.verify~id=' + result);
                        }.bind(this)
                    });
                }
            }
        ),

        /**
         * 操作按钮控件。
         * 筛选框动态的响应用户的输入并提供选择，用户不输入时 filter 表现与普通的输入框相同。
         * options 属性：
         * bType   业务类型，1：合同；2：订单；3：票务；4：结算单 5：厂牌结算单；6：单据
         * cType   操作类型，-1：删除，0：撤销，1：提交，2：驳回，3：通过，4：中止
         * tip     操作玩提示信息
         * @control
         */
        ApprovalSubmitBtn: core.inherits(
            ui.Button,
            function (el, options) {
                ui.Button.call(this, el, options);
                this._sOptId = options.optId;
                this._sCType = options.cType;
                this._sTip = options.tip;
            },
            {
                onkeydown: function (event) {
                    if (event.which === 13) {
                        util.timer(function () {
                            // ecui.dispatchEvent(this, 'blur');
                            core.setFocused();
                        }, 0, this);
                        ecui.dispatchEvent(this, 'submit');
                    }
                },
                onclick: function (event) {
                    ecui.dispatchEvent(this, 'submit');
                    event.stopPropagation();
                },
                onsubmit: function () {
                    if (this._bRequest) {
                        return;
                    }
                    var text = ['', '', '拒绝', '同意']; // 0-撤销 1-提交 2-驳回 3-通过 4-中止

                    this._bRequest = true;
                    ecui.confirm(
                        '是否' + text[this._sCType],
                        function () {
                            ecui.esr.request(
                                util.stringFormat('data@JSON /erp-management/audit/operate?id={0}&action={1}', this._sOptId, this._sCType),
                                function () {
                                    this._bRequest = false;
                                    var data = ecui.esr.getData('data');
                                    if (data instanceof Object) {
                                        ecui.tip('warn', this._sTip);
                                        var item = this.getParent();
                                        item.getParent().remove(item);
                                        // this.afterActionRequest();
                                    }
                                }.bind(this),
                                function () {
                                    this._bRequest = false;
                                    return false;
                                }.bind(this)
                            );
                        }.bind(this),
                        function () {
                            this._bRequest = false;
                        }.bind(this)
                    );
                }
            }
        ),
        TodoCont: ecui.inherits(
            ui.Control,
            {
                oncomplete: function () {
                    ecui.esr.callRoute('todoCont', true);
                }
            }
        )
    });
    ecui.esr.addRoute('index', {
        model: [
            'venues@GET /erp-management/venue/select-list-all',
            'approvalCounts@GET /erp-management/index/h5/play-approval-count'
        ],
        main: 'nav_tab_index',
        view: 'index',
        children: ['todoCont', 'statistics'],
        weight: 1,
        onbeforerender: function (context) {
            context.mtype = 'month';
            this.mtype = 'month';
        },
        onafterrender: function (context) {
            var now = new Date(),
                form = document.forms.indexStatisticsForm,
                elements = form.elements,
                textEl = dom.children(form)[1];

            this.year = now.getFullYear();
            this.index = now.getMonth() + 1;

            elements.startDate.value = new Date(this.year, this.index - 1, 1).pattern('yyyy-MM-dd');
            elements.endDate.value = new Date(this.year, this.index, 0).pattern('yyyy-MM-dd');

            textEl.innerHTML = '月收入' + this.year + '年' + this.index + '月';

        },
        oncached: function (context) {
            if (this.refreshPage) {
                location.reload();
            }
            if (this.mtype) {
                context.mtype = this.mtype;
            } else {
                delete context.mtype;
            }
            if (this.statistics) {
                delete this.statistics;
                ecui.esr.callRoute('/home/statistics', true);
            }
        }
    });
    ecui.esr.addRoute('statistics', {
        model: [
            'statistics@FORM /erp-management/index/h5/data?indexStatisticsForm'
        ],
        main: 'statistics_container',
        view: 'statistics',
        onbeforerequest: function (context) {
            // console.log(period);
        },
        onbeforerender: function (context) {
            context.statistics.total = mao.util.toFixed(context.statistics.totalPrice + context.statistics.drinksSumOfMoney);
        }
    });
    ecui.esr.addRoute('todoCont', {
        model: [
            'todoList@JSON /erp-management/todo/event/list?pageSize=1&pageNo=1&tag=2'
        ],
        main: 'todoCont',
        view: 'todoCont',
        onbeforerequest: function (context) {
        },
        onbeforerender: function (context) {
        }
    });
}());
